package com.zhouyer.sqlSession;

import com.zhouyer.config.BoundSql;
import com.zhouyer.pojo.Configuration;
import com.zhouyer.pojo.MappedStatement;
import com.zhouyer.utils.GenericTokenParser;
import com.zhouyer.utils.ParameterMapping;
import com.zhouyer.utils.ParameterMappingTokenHandler;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class SimpleExecutor implements Executor {
    @Override
    public <E> List<E> query(Configuration configuration, MappedStatement mappedStatement, Object... params) throws SQLException, ClassNotFoundException, NoSuchFieldException, IllegalAccessException, IntrospectionException, InvocationTargetException, InstantiationException {
        // 本质就是使用JDBC进行与数据库交互

        // 1、获取到数据库链接
        Connection connection = configuration.getDataSource().getConnection();
        // 2、解析sql
        // 将 mapper.xml中的sql语句：select * from user where id = #{id} and username =#{username}
        // 解析为JDBC能够使用的sql语句：select * from user where id = ? and username = ? 这里就进行转换，将#{}里面的值进行解析存储
        String sql = mappedStatement.getSql();
        // 专门进行解析sql
        BoundSql boundSql = getBoundSql(sql);

        // 3、获取预处理对象 PreparedStatement
        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSqlText());

        // 4、设置参数
        String beanUrl = mappedStatement.getParameterType();
        Class<?> parameterClassType = getClassType(beanUrl);
        List<ParameterMapping> parameterMappings = boundSql.getParameterMappingList();
        for (int i = 0; i < parameterMappings.size(); i++) {
            ParameterMapping parameterMapping = parameterMappings.get(i);
            String fieldName = parameterMapping.getContent();
            // 使用反射或内省
            Field declaredField = parameterClassType.getDeclaredField(fieldName);
            // 暴力访问
            declaredField.setAccessible(true);
            Object o = declaredField.get(params[0]);
            // 给占位符赋值
            preparedStatement.setObject(i + 1, o);
        }
        // 5、执行sql
        ResultSet resultSet = preparedStatement.executeQuery();
        // 6、封装结果
        String resultType = mappedStatement.getResultType();
        Class<?> resultTypeClass = getClassType(resultType);
        List<Object> objects = new ArrayList<>();
        while (resultSet.next()) {
            Object o = resultTypeClass.newInstance();
            // 获取元数据，因为元数据中有具体的数据字段
            ResultSetMetaData metaData = resultSet.getMetaData();
            for (int i = 1; i <= metaData.getColumnCount(); i++) {
                // 结果集中的字段名
                String columnName = metaData.getColumnName(i);
                // 结果集中字段名对应的值
                Object value = resultSet.getObject(columnName);

                // 使用反射或内省，根据数据库表的字段和实体的对应关系，封装返回结果
                PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columnName, resultTypeClass);
                Method writeMethod = propertyDescriptor.getWriteMethod();
                writeMethod.invoke(o, value);
            }
            objects.add(o);
        }
        return (List<E>) objects;
    }

    /**
     * 更新记录
     *
     * @param configuration   配置（包括数据库配置和sql映射配置）
     * @param mappedStatement sql映射对象
     * @param params          更新的实体参数
     * @return
     */
    @Override
    public int update(Configuration configuration, MappedStatement mappedStatement, Object... params) throws SQLException, ClassNotFoundException, NoSuchFieldException, IllegalAccessException {
        // JDBC相关的操作
        // 1、获取数据库链接
        Connection connection = configuration.getDataSource().getConnection();
        // 2、解析sql
        // insert into user(id,username) values (#{id},#{username})
        BoundSql boundSql = getBoundSql(mappedStatement.getSql());
        // 3、获取预处理对象PreparedStatement
        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSqlText());
        // 设置参数
        // 获取参数类型
        Class<?> parameterType = getClassType(mappedStatement.getParameterType());
        List<ParameterMapping> parameterMappingList = boundSql.getParameterMappingList();
        Object object = params[0];
        if (Integer.class.equals(object.getClass())) {
            preparedStatement.setObject(1, object);
        } else {
            for (int i = 0; i < parameterMappingList.size(); i++) {
                ParameterMapping parameterMapping = parameterMappingList.get(i);
                String fieldName = parameterMapping.getContent();
                // 反射或内省
                Field declaredField = parameterType.getDeclaredField(fieldName);
                //暴力访问
                declaredField.setAccessible(true);
                Object o = declaredField.get(object);
                // 给占位符赋值
                preparedStatement.setObject(i + 1, o);
            }
        }
        //3、执行sql
        return preparedStatement.executeUpdate();
    }

    private Class<?> getClassType(String beanUrl) throws ClassNotFoundException {
        if (null != beanUrl) {
            return Class.forName(beanUrl);
        }
        return null;
    }

    /**
     * 完成对#{}的解析工作：1、将#{}用?来替换;2、解析并存储#{}里面的值
     *
     * @param sql mapper.xml中的sql语句
     * @return
     */
    private BoundSql getBoundSql(String sql) {
        // 实例化一个标记处理类
        ParameterMappingTokenHandler parameterMappingTokenHandler = new ParameterMappingTokenHandler();
        GenericTokenParser genericTokenParser = new GenericTokenParser("#{", "}", parameterMappingTokenHandler);
        // 解析后的参数
        String parseSql = genericTokenParser.parse(sql);
        // 解析后的占位符对应的参数名称
        List<ParameterMapping> parameterMappings = parameterMappingTokenHandler.getParameterMappings();

        return new BoundSql(parseSql, parameterMappings);
    }
}
